package com.example.qbb01;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    private EditText edtPhone, edtPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        edtPhone = findViewById(R.id.edtPhone);
        edtPassword = findViewById(R.id.edtPassword);
        findViewById(R.id.tvRegister).setOnClickListener(view -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivityForResult(intent, 1001);
        });
        findViewById(R.id.btnLogin).setOnClickListener(view -> clickLoginButton());
    }

    /**
     * 点击登录按钮
     */
    private void clickLoginButton() {
        if (edtPhone.getText().toString().trim().isEmpty()) {
            Toast.makeText(LoginActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
        } else if (edtPassword.getText().toString().trim().isEmpty()) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
        } else {
            String phone = edtPhone.getText().toString();
            String password = edtPassword.getText().toString();
            doLoginHttp(phone, password);
        }
    }

    /**
     * 执行登录网络请求
     *
     * @param phone
     * @param password
     */
    private void doLoginHttp(String phone, String password) {
        // 不能再主线程中执行网络请求操作，需求单独新建线程执行网络操作
        new Thread(() -> {
            String urlStr = "https://www.wanandroid.com/user/login";
            String paramsStr = "username=" + phone + "&password=" + password;
            HttpUtils.doPost(urlStr, paramsStr, () -> {
                // 不能再自定义线程中操作UI，需求切回UIThread
                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show());
            });
        }).start();
    }

    /**
     * 复写此方法，接收注册界面（RegisterActivity）回传参数
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // resultCode == RESULT_OK 说明注册页面有数据回传
        // requestCode == 1001  说明回传参数是回传给LoginActivity
        if (resultCode == RESULT_OK && requestCode == 1001) {
            String phone = (String) data.getExtras().get("phone");
            String password = (String) data.getExtras().get("password");
            edtPhone.setText(phone);
            edtPassword.setText(password);
        }
    }
}